/**
 * 性能监控工具类
 * 用于监控应用的各项性能指标，包括启动时间、页面加载时间、内存使用等
 */

class PerformanceMonitor {
  constructor() {
    // 性能数据存储
    this.performanceData = {
      appStart: 0,
      appReady: 0,
      appShow: 0,
      pageLoadTimes: {},
      memoryUsage: [],
      networkRequests: [],
      fpsRecords: []
    };
    
    // FPS 计算相关
    this.frameCount = 0;
    this.lastTime = 0;
    this.fpsInterval = null;
    this.fpsThreshold = 30; // FPS 警告阈值
    
    // 内存监控相关
    this.memoryMonitorInterval = null;
    this.memoryWarningThreshold = 100; // 内存警告阈值（MB）
    
    // 网络监控相关
    this.networkMonitorEnabled = false;
    this.originalRequest = null;
    
    // 是否启用性能监控
    this.enabled = false;
    
    // 是否处于调试模式
    this.debugMode = false;
  }
  
  /**
   * 初始化性能监控
   * @param {Object} options - 配置选项
   * @param {boolean} options.debug - 是否启用调试模式
   * @param {number} options.fpsMonitorInterval - FPS监控间隔（毫秒）
   * @param {number} options.memoryMonitorInterval - 内存监控间隔（毫秒）
   */
  init(options = {}) {
    this.enabled = true;
    this.debugMode = !!options.debug;
    
    // 记录应用启动时间
    this.performanceData.appStart = Date.now();
    
    // 监控应用生命周期
    this.monitorAppLifecycle();
    
    // 监控页面生命周期
    this.monitorPageLifecycle();
    
    // 启动FPS监控
    if (options.fpsMonitorInterval !== false) {
      this.startFpsMonitor(options.fpsMonitorInterval || 1000);
    }
    
    // 启动内存监控
    if (options.memoryMonitorInterval !== false) {
      this.startMemoryMonitor(options.memoryMonitorInterval || 5000);
    }
    
    // 启用网络请求监控
    if (options.networkMonitor !== false) {
      this.enableNetworkMonitor();
    }
    
    if (this.debugMode) {
      console.log('性能监控已初始化', this.performanceData);
    }
  }
  
  /**
   * 监控应用生命周期
   */
  monitorAppLifecycle() {
    // 监听应用就绪事件
    uni.onAppShow((res) => {
      if (!this.performanceData.appShow) {
        this.performanceData.appShow = Date.now();
        const appLaunchTime = this.performanceData.appShow - this.performanceData.appStart;
        
        if (this.debugMode) {
          console.log(`应用启动耗时: ${appLaunchTime}ms`);
        }
        
        // 记录启动性能指标
        this.recordMetric('app_launch_time', appLaunchTime);
      }
    });
    
    // 监听应用隐藏事件
    uni.onAppHide(() => {
      // 应用进入后台时暂停某些监控
      this.pauseMonitors();
    });
    
    // 监听应用错误
    uni.onError((error) => {
      this.recordError('app_error', error);
    });
  }
  
  /**
   * 监控页面生命周期
   */
  monitorPageLifecycle() {
    // 重写页面生命周期钩子，记录页面加载时间
    const originalPage = Page;
    
    Page = (config) => {
      const originalOnLoad = config.onLoad;
      const originalOnReady = config.onReady;
      const originalOnShow = config.onShow;
      const originalOnHide = config.onHide;
      const originalOnUnload = config.onUnload;
      
      // 页面加载时间记录
      let pageLoadStart = 0;
      let pageLoadEnd = 0;
      let pageReadyTime = 0;
      
      // 重写 onLoad
      config.onLoad = function(options) {
        pageLoadStart = Date.now();
        
        if (originalOnLoad) {
          originalOnLoad.call(this, options);
        }
      };
      
      // 重写 onReady
      config.onReady = function() {
        pageReadyTime = Date.now();
        const readyTime = pageReadyTime - pageLoadStart;
        
        if (this.$options?.name || this.route) {
          const pageName = this.$options?.name || this.route.split('/').pop();
          
          if (!performanceMonitor.performanceData.pageLoadTimes[pageName]) {
            performanceMonitor.performanceData.pageLoadTimes[pageName] = [];
          }
          
          performanceMonitor.performanceData.pageLoadTimes[pageName].push({
            timestamp: Date.now(),
            readyTime,
            fullLoadTime: null
          });
          
          performanceMonitor.recordMetric('page_ready_time', readyTime, { page: pageName });
          
          if (performanceMonitor.debugMode) {
            console.log(`页面 ${pageName} 就绪耗时: ${readyTime}ms`);
          }
        }
        
        if (originalOnReady) {
          originalOnReady.call(this);
        }
      };
      
      // 重写 onShow
      config.onShow = function() {
        performanceMonitor.resumeMonitors();
        
        if (originalOnShow) {
          originalOnShow.call(this);
        }
      };
      
      // 重写 onHide
      config.onHide = function() {
        performanceMonitor.pauseMonitors();
        
        if (originalOnHide) {
          originalOnHide.call(this);
        }
      };
      
      // 重写 onUnload
      config.onUnload = function() {
        pageLoadEnd = Date.now();
        const fullLoadTime = pageLoadEnd - pageLoadStart;
        
        if (this.$options?.name || this.route) {
          const pageName = this.$options?.name || this.route.split('/').pop();
          const lastPageLoad = performanceMonitor.performanceData.pageLoadTimes[pageName]?.pop();
          
          if (lastPageLoad) {
            lastPageLoad.fullLoadTime = fullLoadTime;
            performanceMonitor.performanceData.pageLoadTimes[pageName].push(lastPageLoad);
            performanceMonitor.recordMetric('page_full_load_time', fullLoadTime, { page: pageName });
          }
        }
        
        if (originalOnUnload) {
          originalOnUnload.call(this);
        }
      };
      
      return originalPage(config);
    };
  }
  
  /**
   * 启动FPS监控
   * @param {number} interval - 监控间隔（毫秒）
   */
  startFpsMonitor(interval = 1000) {
    if (!wx || !wx.createSelectorQuery) {
      if (this.debugMode) {
        console.log('当前环境不支持FPS监控');
      }
      return;
    }
    
    let lastTime = Date.now();
    let frameCount = 0;
    
    const calculateFPS = () => {
      if (!this.enabled) return;
      
      frameCount++;
      const now = Date.now();
      
      if (now - lastTime >= interval) {
        const fps = Math.round((frameCount * 1000) / (now - lastTime));
        
        this.performanceData.fpsRecords.push({
          timestamp: now,
          fps
        });
        
        // 只保留最近100条FPS记录
        if (this.performanceData.fpsRecords.length > 100) {
          this.performanceData.fpsRecords.shift();
        }
        
        // 如果FPS低于阈值，记录警告
        if (fps < this.fpsThreshold) {
          this.recordWarning('low_fps', { fps, threshold: this.fpsThreshold });
          
          if (this.debugMode) {
            console.warn(`FPS过低: ${fps}fps (阈值: ${this.fpsThreshold}fps)`);
          }
        }
        
        // 记录FPS指标
        this.recordMetric('fps', fps);
        
        frameCount = 0;
        lastTime = now;
      }
      
      this.fpsInterval = requestAnimationFrame(calculateFPS);
    };
    
    calculateFPS();
  }
  
  /**
   * 启动内存监控
   * @param {number} interval - 监控间隔（毫秒）
   */
  startMemoryMonitor(interval = 5000) {
    this.memoryMonitorInterval = setInterval(() => {
      if (!this.enabled) return;
      
      // 在微信小程序环境中获取内存信息
      if (wx && wx.getSystemInfoSync) {
        try {
          const systemInfo = wx.getSystemInfoSync();
          const memoryInfo = wx.getStorageInfoSync();
          
          const memoryData = {
            timestamp: Date.now(),
            storageInfo: memoryInfo,
            systemInfo: {
              platform: systemInfo.platform,
              system: systemInfo.system,
              version: systemInfo.version
            }
          };
          
          this.performanceData.memoryUsage.push(memoryData);
          
          // 只保留最近50条内存记录
          if (this.performanceData.memoryUsage.length > 50) {
            this.performanceData.memoryUsage.shift();
          }
          
          // 检查存储空间是否不足
          if (memoryInfo.currentSize > memoryInfo.limitSize * 0.9) {
            this.recordWarning('storage_almost_full', {
              currentSize: memoryInfo.currentSize,
              limitSize: memoryInfo.limitSize
            });
            
            if (this.debugMode) {
              console.warn('存储空间即将用完');
            }
          }
        } catch (error) {
          console.error('获取内存信息失败:', error);
        }
      }
    }, interval);
  }
  
  /**
   * 启用网络请求监控
   */
  enableNetworkMonitor() {
    if (this.networkMonitorEnabled) return;
    
    this.networkMonitorEnabled = true;
    
    // 保存原始的请求方法
    const originalRequest = uni.request;
    
    // 重写请求方法
    uni.request = (options) => {
      const requestStart = Date.now();
      const requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // 记录请求开始
      const requestInfo = {
        id: requestId,
        url: options.url,
        method: options.method || 'GET',
        startTime: requestStart,
        endTime: null,
        duration: null,
        statusCode: null,
        success: false,
        error: null
      };
      
      // 保存原始的回调函数
      const originalSuccess = options.success;
      const originalFail = options.fail;
      const originalComplete = options.complete;
      
      // 重写 success 回调
      options.success = (res) => {
        const requestEnd = Date.now();
        requestInfo.endTime = requestEnd;
        requestInfo.duration = requestEnd - requestStart;
        requestInfo.statusCode = res.statusCode;
        requestInfo.success = true;
        
        // 记录请求
        this.performanceData.networkRequests.push(requestInfo);
        
        // 只保留最近200条网络请求记录
        if (this.performanceData.networkRequests.length > 200) {
          this.performanceData.networkRequests.shift();
        }
        
        // 记录网络性能指标
        this.recordMetric('network_request_duration', requestInfo.duration, {
          url: requestInfo.url,
          method: requestInfo.method,
          statusCode: requestInfo.statusCode
        });
        
        // 如果响应时间过长，记录警告
        if (requestInfo.duration > 3000) { // 3秒
          this.recordWarning('slow_network_request', {
            url: requestInfo.url,
            duration: requestInfo.duration
          });
          
          if (this.debugMode) {
            console.warn(`网络请求过慢: ${requestInfo.url} (${requestInfo.duration}ms)`);
          }
        }
        
        // 调用原始的 success 回调
        if (originalSuccess) {
          originalSuccess(res);
        }
      };
      
      // 重写 fail 回调
      options.fail = (err) => {
        const requestEnd = Date.now();
        requestInfo.endTime = requestEnd;
        requestInfo.duration = requestEnd - requestStart;
        requestInfo.error = err;
        requestInfo.success = false;
        
        // 记录请求
        this.performanceData.networkRequests.push(requestInfo);
        
        // 记录错误
        this.recordError('network_request_failed', {
          url: requestInfo.url,
          error: err
        });
        
        // 调用原始的 fail 回调
        if (originalFail) {
          originalFail(err);
        }
      };
      
      // 重写 complete 回调
      options.complete = (res) => {
        // 调用原始的 complete 回调
        if (originalComplete) {
          originalComplete(res);
        }
      };
      
      // 调用原始的请求方法
      return originalRequest(options);
    };
  }
  
  /**
   * 暂停监控
   */
  pauseMonitors() {
    if (this.fpsInterval) {
      cancelAnimationFrame(this.fpsInterval);
      this.fpsInterval = null;
    }
  }
  
  /**
   * 恢复监控
   */
  resumeMonitors() {
    if (!this.fpsInterval && this.enabled) {
      this.startFpsMonitor();
    }
  }
  
  /**
   * 记录性能指标
   * @param {string} name - 指标名称
   * @param {number} value - 指标值
   * @param {Object} extra - 额外信息
   */
  recordMetric(name, value, extra = {}) {
    // 这里可以将性能指标上报到服务器
    // 在实际项目中，可以根据需要实现上报逻辑
    if (this.debugMode) {
      console.log(`性能指标: ${name} = ${value}`, extra);
    }
  }
  
  /**
   * 记录警告
   * @param {string} type - 警告类型
   * @param {Object} details - 警告详情
   */
  recordWarning(type, details = {}) {
    const warning = {
      type,
      timestamp: Date.now(),
      details
    };
    
    // 这里可以将警告上报到服务器
    if (this.debugMode) {
      console.warn(`性能警告: ${type}`, details);
    }
  }
  
  /**
   * 记录错误
   * @param {string} type - 错误类型
   * @param {*} error - 错误信息
   */
  recordError(type, error) {
    const errorInfo = {
      type,
      timestamp: Date.now(),
      error: typeof error === 'string' ? error : JSON.stringify(error)
    };
    
    // 这里可以将错误上报到服务器
    if (this.debugMode) {
      console.error(`性能错误: ${type}`, error);
    }
  }
  
  /**
   * 获取性能报告
   * @returns {Object} 性能数据报告
   */
  getPerformanceReport() {
    return {
      summary: {
        appLaunchTime: this.performanceData.appShow ? 
          this.performanceData.appShow - this.performanceData.appStart : null,
        totalPageLoads: Object.values(this.performanceData.pageLoadTimes)
          .reduce((sum, times) => sum + times.length, 0),
        totalNetworkRequests: this.performanceData.networkRequests.length,
        averageFps: this.calculateAverageFps()
      },
      details: {
        pageLoadTimes: this.performanceData.pageLoadTimes,
        networkRequests: this.performanceData.networkRequests.slice(-50), // 只返回最近50条
        memoryUsage: this.performanceData.memoryUsage.slice(-20), // 只返回最近20条
        fpsRecords: this.performanceData.fpsRecords.slice(-30) // 只返回最近30条
      }
    };
  }
  
  /**
   * 计算平均FPS
   * @returns {number} 平均FPS值
   */
  calculateAverageFps() {
    if (this.performanceData.fpsRecords.length === 0) return 0;
    
    const sum = this.performanceData.fpsRecords
      .reduce((total, record) => total + record.fps, 0);
    
    return Math.round(sum / this.performanceData.fpsRecords.length);
  }
  
  /**
   * 清除所有性能数据
   */
  clearPerformanceData() {
    this.performanceData = {
      appStart: this.performanceData.appStart, // 保留应用启动时间
      appReady: this.performanceData.appReady,
      appShow: this.performanceData.appShow,
      pageLoadTimes: {},
      memoryUsage: [],
      networkRequests: [],
      fpsRecords: []
    };
  }
  
  /**
   * 停止所有监控
   */
  stop() {
    this.enabled = false;
    
    // 停止FPS监控
    if (this.fpsInterval) {
      cancelAnimationFrame(this.fpsInterval);
      this.fpsInterval = null;
    }
    
    // 停止内存监控
    if (this.memoryMonitorInterval) {
      clearInterval(this.memoryMonitorInterval);
      this.memoryMonitorInterval = null;
    }
    
    // 恢复原始请求方法
    if (this.networkMonitorEnabled && this.originalRequest) {
      uni.request = this.originalRequest;
      this.networkMonitorEnabled = false;
    }
    
    if (this.debugMode) {
      console.log('性能监控已停止');
    }
  }
  
  /**
   * 触发垃圾回收（在支持的环境中）
   * 注意：在实际的UniApp环境中，这可能不会生效，因为JavaScript引擎通常不允许手动触发GC
   */
  triggerGarbageCollection() {
    if (wx && wx.triggerGC) {
      try {
        wx.triggerGC();
        if (this.debugMode) {
          console.log('尝试触发垃圾回收');
        }
      } catch (error) {
        console.error('触发垃圾回收失败:', error);
      }
    } else if (this.debugMode) {
      console.log('当前环境不支持手动触发垃圾回收');
    }
  }
}

// 导出单例实例
const performanceMonitor = new PerformanceMonitor();

export default performanceMonitor;

// 导出性能优化相关的辅助函数
export const performanceUtils = {
  /**
   * 防抖函数
   * @param {Function} func - 要执行的函数
   * @param {number} delay - 延迟时间（毫秒）
   * @returns {Function} 防抖后的函数
   */
  debounce(func, delay = 300) {
    let timeoutId;
    return function(...args) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
  },
  
  /**
   * 节流函数
   * @param {Function} func - 要执行的函数
   * @param {number} limit - 时间限制（毫秒）
   * @returns {Function} 节流后的函数
   */
  throttle(func, limit = 300) {
    let inThrottle;
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  },
  
  /**
   * 预加载图片
   * @param {Array} images - 图片URL数组
   * @returns {Promise} 预加载完成的Promise
   */
  preloadImages(images) {
    if (!Array.isArray(images) || images.length === 0) {
      return Promise.resolve();
    }
    
    const promises = images.map(src => {
      return new Promise((resolve, reject) => {
        if (typeof wx !== 'undefined') {
          // 微信小程序环境
          wx.getImageInfo({
            src,
            success: () => resolve(src),
            fail: (err) => {
              console.warn(`预加载图片失败: ${src}`, err);
              resolve(src); // 即使失败也继续
            }
          });
        } else {
          // Web环境
          const img = new Image();
          img.onload = () => resolve(src);
          img.onerror = () => {
            console.warn(`预加载图片失败: ${src}`);
            resolve(src); // 即使失败也继续
          };
          img.src = src;
        }
      });
    });
    
    return Promise.all(promises);
  },
  
  /**
   * 延迟执行
   * @param {number} ms - 延迟时间（毫秒）
   * @returns {Promise} 延迟完成的Promise
   */
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  },
  
  /**
   * 批量处理数据，避免一次性处理过多数据导致页面卡顿
   * @param {Array} items - 要处理的数组
   * @param {Function} processItem - 处理单个项目的函数
   * @param {number} batchSize - 每批处理的数量
   * @param {number} delayMs - 批次间隔时间（毫秒）
   * @returns {Promise} 所有项目处理完成的Promise
   */
  async batchProcess(items, processItem, batchSize = 10, delayMs = 50) {
    if (!Array.isArray(items)) {
      throw new Error('items参数必须是数组');
    }
    
    const results = [];
    
    for (let i = 0; i < items.length; i += batchSize) {
      const batch = items.slice(i, i + batchSize);
      const batchResults = await Promise.all(batch.map(processItem));
      results.push(...batchResults);
      
      // 如果不是最后一批，添加延迟
      if (i + batchSize < items.length) {
        await this.delay(delayMs);
      }
    }
    
    return results;
  }
};